package com.example.player.ui.home;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.player.R;
import com.example.player.adapter.FileListAdapter;
import com.example.player.databinding.FragmentHomeBinding;
import com.example.player.model.FileItem;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";

    private FragmentHomeBinding binding;
    private ExoPlayer player;
    private PlayerView playerView;
    private EditText urlInput;
    private Button playButton;
    private Button stopButton;
    private FloatingActionButton fabFileList;
    private static final String RTSP_PORT = "8554";
    private static final String RTSP_PATH = "stream";
    private static final String HTTP_PORT = "5000";
    private String currentServerIp;
    private String currentPath = "/media/sdcard/recordings";
    private ExecutorService executorService;
    private Dialog fileListDialog;

    public View onCreateView(@NonNull LayoutInflater inflater,
                           ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化视图
        playerView = binding.playerView;
        urlInput = binding.urlInput;
        playButton = binding.playButton;
        stopButton = binding.stopButton;
        fabFileList = binding.fabFileList;

        // 初始化线程池
        executorService = Executors.newSingleThreadExecutor();

        // 初始化播放器
        player = new ExoPlayer.Builder(requireContext()).build();
        playerView.setPlayer(player);

        // 设置播放按钮点击事件
        playButton.setOnClickListener(v -> {
            String ip = urlInput.getText().toString().trim();
            if (!ip.isEmpty()) {
                currentServerIp = ip;
                String rtspUrl = buildRtspUrl(ip);
                Log.d(TAG, "RTSP URL: " + rtspUrl);
                playRtspStream(rtspUrl, false);
            } else {
                Toast.makeText(requireContext(), "请输入服务器IP地址", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置停止按钮点击事件
        stopButton.setOnClickListener(v -> {
            if (player != null) {
                player.stop();
                player.clearMediaItems();
            }
        });

        // 设置文件列表按钮点击事件
        fabFileList.setOnClickListener(v -> {
            if (currentServerIp != null && !currentServerIp.isEmpty()) {
                showFileListDialog();
            } else {
                Toast.makeText(requireContext(), "请先输入服务器IP地址", Toast.LENGTH_SHORT).show();
            }
        });

        return root;
    }

    private void showFileListDialog() {
        fileListDialog = new Dialog(requireContext());
        fileListDialog.setContentView(R.layout.dialog_file_list);
        fileListDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 
                ViewGroup.LayoutParams.WRAP_CONTENT);

        TextView currentPathView = fileListDialog.findViewById(R.id.current_path);
        RecyclerView fileListView = fileListDialog.findViewById(R.id.file_list);
        ImageButton btnBack = fileListDialog.findViewById(R.id.btn_back);
        
        currentPathView.setText("当前路径: " + currentPath);
        fileListView.setLayoutManager(new LinearLayoutManager(requireContext()));
        
        // 根据当前路径决定是否显示返回按钮
        btnBack.setVisibility(currentPath.equals("/media/sdcard/recordings") ? View.GONE : View.VISIBLE);
        
        // 设置返回按钮点击事件
        btnBack.setOnClickListener(v -> {
            if (!currentPath.equals("/media/sdcard/recordings")) {
                // 获取上级目录路径
                String parentPath = currentPath.substring(0, currentPath.lastIndexOf("/"));
                if (parentPath.isEmpty()) {
                    parentPath = "/media/sdcard/recordings";
                }
                currentPath = parentPath;
                currentPathView.setText("当前路径: " + currentPath);
                // 更新返回按钮显示状态
                btnBack.setVisibility(currentPath.equals("/media/sdcard/recordings") ? View.GONE : View.VISIBLE);
                loadFileList(currentPath, fileListView, currentPathView, btnBack);
            }
        });
        
        loadFileList(currentPath, fileListView, currentPathView, btnBack);
        
        fileListDialog.show();
    }

    private void loadFileList(String path, RecyclerView fileListView, TextView currentPathView, ImageButton btnBack) {
        executorService.execute(() -> {
            try {
                String url = String.format("http://%s:%s/api/list?dir=%s", currentServerIp, HTTP_PORT, path);
                Log.d(TAG, "Requesting file list from: " + url);
                
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setRequestMethod("GET");
                Log.d(TAG, "HTTP Response Code: " + connection.getResponseCode());

                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();

                    Log.d(TAG, "File list response: " + response.toString());

                    JSONObject jsonResponse = new JSONObject(response.toString());
                    List<FileItem> fileItems = new ArrayList<>();

                    // 处理文件夹
                    if (jsonResponse.has("folders")) {
                        JSONArray folders = jsonResponse.getJSONArray("folders");
                        for (int i = 0; i < folders.length(); i++) {
                            JSONObject folder = folders.getJSONObject(i);
                            String name = folder.getString("name");
                            // 确保路径以/分隔，但不以/结尾
                            String folderPath = path.endsWith("/") ? path + name : path + "/" + name;
                            fileItems.add(new FileItem(name, folderPath, true));
                        }
                    }

                    // 处理文件
                    if (jsonResponse.has("files")) {
                        JSONArray files = jsonResponse.getJSONArray("files");
                        for (int i = 0; i < files.length(); i++) {
                            JSONObject file = files.getJSONObject(i);
                            String name = file.getString("name");
                            // 确保路径以/分隔
                            String filePath = path.endsWith("/") ? path + name : path + "/" + name;
                            fileItems.add(new FileItem(name, filePath, false));
                        }
                    }

                    Log.d(TAG, "Found " + fileItems.size() + " items in directory");

                    requireActivity().runOnUiThread(() -> {
                        FileListAdapter adapter = new FileListAdapter(fileItems, fileItem -> {
                            if (fileItem.isDirectory()) {
                                currentPath = fileItem.getPath();
                                currentPathView.setText("当前路径: " + currentPath);
                                // 更新返回按钮显示状态
                                btnBack.setVisibility(currentPath.equals("/media/sdcard/recordings") ? View.GONE : View.VISIBLE);
                                loadFileList(currentPath, fileListView, currentPathView, btnBack);
                            } else {
                                String videoUrl = String.format("http://%s:%s/api/push?path=%s", 
                                        currentServerIp, HTTP_PORT, fileItem.getPath());
                                Log.d(TAG, "Playing video from: " + videoUrl);
                                // 发送POST请求启动推流
                                executorService.execute(() -> {
                                    try {
                                        HttpURLConnection pushConnection = (HttpURLConnection) new URL(videoUrl).openConnection();
                                        pushConnection.setRequestMethod("POST");
                                        int responseCode = pushConnection.getResponseCode();
                                        Log.d(TAG, "Push API Response Code: " + responseCode);
                                        
                                        if (responseCode == HttpURLConnection.HTTP_OK) {
                                            // 推流启动成功后播放RTSP流
                                            String rtspUrl = String.format("rtsp://%s:%s/stream%s", 
                                                    currentServerIp, RTSP_PORT, fileItem.getPath());
                                            Log.d(TAG, "Starting RTSP stream: " + rtspUrl);
                                            requireActivity().runOnUiThread(() -> {
                                                // 延迟2秒后播放RTSP流
                                                new Handler().postDelayed(() -> {
                                                    playRtspStream(rtspUrl, true);
                                                }, 2000);
                                                fileListDialog.dismiss();
                                            });
                                        } else {
                                            requireActivity().runOnUiThread(() -> {
                                                Toast.makeText(requireContext(), "启动推流失败", Toast.LENGTH_SHORT).show();
                                            });
                                        }
                                    } catch (IOException e) {
                                        Log.e(TAG, "Error starting stream", e);
                                        requireActivity().runOnUiThread(() -> {
                                            Toast.makeText(requireContext(), "启动推流失败: " + e.getMessage(), 
                                                    Toast.LENGTH_SHORT).show();
                                        });
                                    }
                                });
                            }
                        });
                        fileListView.setAdapter(adapter);
                    });
                }
            } catch (IOException | JSONException e) {
                Log.e(TAG, "Error loading file list", e);
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireContext(), "加载文件列表失败: " + e.getMessage(), 
                            Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void playVideo(String videoUrl) {
        Log.d(TAG, "Starting video playback: " + videoUrl);
        MediaItem mediaItem = MediaItem.fromUri(videoUrl);
        player.setMediaItem(mediaItem);
        player.prepare();
        player.play();
    }

    private String buildRtspUrl(String ip) {
        return String.format("rtsp://%s:%s/%s", ip, RTSP_PORT, RTSP_PATH);
    }

    private void playRtspStream(String url, boolean isAutoStop) {
        Log.d(TAG, "Starting RTSP stream: " + url);
        MediaItem mediaItem = MediaItem.fromUri(url);
        player.setMediaItem(mediaItem);
        player.prepare();
        player.play();
        
        if (isAutoStop) {
        // 添加播放器监听器
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                if (state == Player.STATE_ENDED || state == Player.STATE_IDLE) {
                    // 停止推流
                    String stopUrl = String.format("http://%s:%s/api/stop?path=%s", 
                            currentServerIp, HTTP_PORT, url.substring(url.indexOf("/stream") + 7));
                    executorService.execute(() -> {
                        try {
                            HttpURLConnection stopConnection = (HttpURLConnection) new URL(stopUrl).openConnection();
                            stopConnection.setRequestMethod("POST");
                            int responseCode = stopConnection.getResponseCode();
                            Log.d(TAG, "Stop stream response code: " + responseCode);
                        } catch (IOException e) {
                            Log.e(TAG, "Error stopping stream", e);
                        }
                    });
                }
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (player != null) {
            player.release();
            player = null;
        }
        if (executorService != null) {
            executorService.shutdown();
        }
        binding = null;
    }
}